package com.will.seed.configuration;

import com.will.seed.websocket.HttpRequestHandler;
import com.will.seed.websocket.TextWebSocketFrameHandler;
import com.will.seed.websocket.WebSocketServer;
import com.will.seed.websocket.WebSocketServerInitializer;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.ImmediateEventExecutor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import java.net.InetSocketAddress;

/**
 * Created by xiaoEight on 2018/8/21.
 */
@Configuration
public class WebSocketAutoConfiguration {

    @Value("${ws.host:127.0.0.1}")
    private String wsHost;

    @Value("${ws.port:9090}")
    private int wsPort;

    @Bean
    public InetSocketAddress inetSocketAddress(){
        return new InetSocketAddress(wsHost, wsPort);
    }

    @Bean
    public WebSocketServer webSocketServer(){
        return new WebSocketServer(channelGroup(),
                webSocketServerInitializer(channelGroup()),
                inetSocketAddress());
    }

    @Bean
    public ChannelGroup channelGroup(){
        return new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
    }

    @Bean
    @Scope(BeanDefinition.SCOPE_PROTOTYPE)
    public TextWebSocketFrameHandler textWebSocketFrameHandler(){
        return new TextWebSocketFrameHandler(channelGroup());
    }

    @Bean
    @Scope(BeanDefinition.SCOPE_PROTOTYPE)
    public HttpRequestHandler httpRequestHandler(){
        return new HttpRequestHandler();
    }

    @Bean
    public WebSocketServerInitializer webSocketServerInitializer(ChannelGroup channelGroup){
        return new WebSocketServerInitializer(channelGroup);
    }


}

